<!DOCTYPE html>
<html lang="zh_CN" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:fragment="head">
	<base th:href="@{/}">
	<meta charset="utf-8">
	<title>新增</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
	<link rel="stylesheet" href="static/layui/css/layui.css" media="all" />
	<script type="text/javascript" src="static/layui/layui.js"></script>
	<script type="text/javascript" src="static/plugin/jquery/jquery-1.4.4.min.js"></script>
	<style type="text/css">
		.layui-form-label {
		    white-space: nowrap;
		    width: 120px;
		    color: gray;
		}
	</style>
</head>
<body>
<div class="layui-fluid">
	<div class="layui-card">
		<!-- 内容区 -->
		<div class="layui-card-body">
			<form class="layui-form" id="form" action="" >
				<div class="layui-card-header">结算单表头信息</div>
				<div class="layui-form-item" style="margin-top: 20px;">
					<div class="layui-inline">
						<label class="layui-form-label"><span style="color: red">*</span>客户编码</label>
						<div class="layui-input-inline">
							<input name="customerCode" id="customerCode" class="layui-input" lay-verify="required" readonly>
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label"><span style="color: red">*</span>客户名称</label>
						<div class="layui-input-inline">
							<input name="customerName" class="layui-input" lay-verify="required" readonly>
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">客户订单号</label>
						<div class="layui-input-inline">
							<input name="customerOrder" class="layui-input" >
						</div>
					</div>
				</div>
				<div class="layui-form-item" style="margin-top: 20px;">
					<div class="layui-inline">
						<label class="layui-form-label"><span style="color: red">*</span>内部订单号</label>
						<div class="layui-input-inline">
							<input name="orderNo" lay-verify="required" class="layui-input" >
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label"><span style="color: red">*</span>销售订单号</label>
						<div class="layui-input-inline">
							<input name="saleOrderNo" id="saleOrderNo" lay-verify="required" class="layui-input" readonly>
							<input name="saleOrderNoId" id="saleOrderNoId" style="display: none" lay-verify="required" class="layui-input" readonly>
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">关联订单号</label>
						<div class="layui-input-inline">
							<input name="relatedOrder" class="layui-input" >
						</div>
					</div>
				</div>
				<div class="layui-form-item" style="margin-top: 20px;">
					<div class="layui-inline">
						<label class="layui-form-label">承揽商</label>
						<div class="layui-input-inline">
							<input name="cls" class="layui-input" >
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">产品类别</label>
						<div class="layui-input-inline">
							<input name="cplb" class="layui-input" >
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">订单属性</label>
						<div class="layui-input-inline">
							<input name="ddsx" class="layui-input" >
						</div>
					</div>
				</div>
				<div class="layui-form-item" style="margin-top: 20px;">
					<div class="layui-inline">
						<label class="layui-form-label">业务员</label>
						<div class="layui-input-inline">
							<input name="personName" class="layui-input" >
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label"><span style="color: red">*</span>制单日期</label>
						<div class="layui-input-inline">
							<input name="createTime" lay-verify="required" class="layui-input" id="ID-laydate-demo" placeholder="yyyy-MM-dd">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label"></label>
						<button type="submit" class="layui-btn" id="submit" style="display: none" lay-submit lay-filter="demo1">立即提交</button>
						<button type="reset" class="layui-btn layui-btn-primary">重置</button>
					</div>
				</div>
			</form>
			<div class="layui-card-header">结算单表体信息</div>
			<div class="layui-row" style="margin-top: 5px;">
				<div class="layui-col-md12">
					<table id="table" class="layui-table" lay-filter="table"></table>
				</div>
			</div>
			<div class="layui-card-header">订单工序信息</div>
			<div class="layui-row" style="margin-top: 5px;">
				<div class="layui-col-md12">
					<table id="processTable" class="layui-table" lay-filter="processTable"></table>
				</div>
			</div>
		</div>
	</div>
	<script type="text/html" id="barRight">
		<a class="layui-btn layui-btn-sm layui-bg-red" lay-event="del">删除</a>
	</script>
	<script type="text/html" id="processTableToolbar">
<!--		<button class="layui-btn layui-btn-sm layui-bg-orange" lay-event="add"><i class="layui-icon">&#xe605;</i>添加</button>-->
	</script>
	<script type="text/html" id="tableToolbar">
		<button class="layui-btn layui-btn-sm layui-bg-orange" lay-event="add"><i class="layui-icon">&#xe605;</i>添加</button>
	</script>
	<script type="text/html" id="TPL-dropdpwn-demo">
		<button class="layui-btn layui-btn-sm layui-btn-primary dropdpwn-demo">
			<span>正常结算</span>
			<i class="layui-icon layui-icon-down layui-font-12"></i>
		</button>
	</script>
	<script type="text/javascript" src="/static/layui/module/tableSelect.js"></script>
	<script type="text/javascript" th:inline="javascript">
		layui.use(['layer','jquery','table','element','form','laydate','tableSelect'],function(){
			let layer = layui.layer,
					table = layui.table,
					form = layui.form,
					laydate = layui.laydate,
					$ = layui.jquery,
					tableSelect = layui.tableSelect,
					dropdown = layui.dropdown,
					element = layui.element;

			let details = []
			let produces = new Map();
			let selectId;
			let tableQty = 0;

			// 渲染
			laydate.render({
				elem: '#ID-laydate-demo'
			});

			tableSelect.render({
				elem: '#customerCode',
				searchKey: 'key',
				searchPlaceholder: '客户编码/客户名称',
				checkedKey: 'code',
				table: {
					url: '/manage/customer/list'
					,method: 'post'
					,cols: [
						[
							{ type: 'radio' },
							{ field: 'code', title: '客户编码' },
							{ field: 'name', title: '客户名称' },
						]
					]
				},
				done: function (elem, data) {
					let da = data.data[0]
					elem.val(da.code)
					$('input[name=customerName]').val(da.name)
				}
			})

			tableSelect.render({
				elem: '#saleOrderNo',
				searchKey: 'key',
				searchPlaceholder: '销售订单号',
				checkedKey: 'orderNo',
				table: {
					url: '/manage/sale_order/listSett'
					,method: 'post'
					,cols: [
						[
							{ type: 'radio' },
							{ field: 'orderNo', title: '销售订单号' },
							{ field: 'ddate', title: '制单日期' },
						]
					]
				},
				done: function (elem, data) {
					let da = data.data[0]
					elem.val(da.orderNo)
					$('#saleOrderNoId').val(da.id)
				}
			})

			// 提交事件
			form.on('submit(demo1)', function(data){
				let field = data.field; // 获取表单字段值

				//校验是否有产品信息
				if (!details.length){
					top.layer.msg("请添加【销售订单表体信息】")
					return false
				}

				let cinvcode = false;
				$.each(details,function (index,item) {
					let proData = produces.get(item.id);
					if (!proData || !proData.length){
						cinvcode = item.cinvcode
						return false
					}
				})
				if (cinvcode){
					top.layer.msg("产品编码【"+cinvcode+"】请添加【订单工序信息】")
					return false
				}

				cinvcode = false;
				let values = produces.values();
				for (i = 0; i < produces.size; i++) {
					let value = values.next().value;
					$.each(value,function (index,item) {
						if (!item.qty){
							cinvcode = true;
						}
					})
				}

				if (cinvcode){
					top.layer.msg("请正确填写【合格数量】与【不合格数量】")
					return false
				}

				$.each(details,function (index,item) {
					item.process = produces.get(item.id);
				})
				//提交数据
				field.details = details

				let itm = top.layer.load(0, { shade: 0.3 });
				$.post({
					url: "/manage/settlement_order/add",
					contentType: "application/json"
				},JSON.stringify(field),function (d) {
					top.layer.close(itm)
					if (d.code === 200){
						top.layer.msg('保存成功！',{time: 800},function () {
							top.layer.closeAll()
						});
					}else {
						top.layer.msg('保存失败！'+ d.msg);
					}
				})

				return false; // 阻止默认 form 跳转
			});

			table.render({
				elem:'#table'
				,page: true //开启分页
				,limit: 10
				,limits: [10,15,20,30,40,50,100]
				,loading: true
				,cols: [
					[ //表头
						{type:'radio'}
						,{field: 'cinvcode', title: '产品编码', minWidth:'150'}
						,{field: 'cinvname', title: '产品名称', minWidth:'150'}
						,{field: 'type', title: '类型', minWidth:'150'}
						,{field: 'settlementType', title: '结算类型', minWidth:'120',templet: '#TPL-dropdpwn-demo'}
						,{field: 'zkv', title: '折扣率(%)', minWidth:'100', edit: true}
						,{field: 'cbatch', title: '批号', minWidth:'150'}
						,{field: 'qty', title: '订单数量', minWidth:'90'}
						,{field: 'completFlag', title: '是否定价', minWidth:'100', templet: function (d){
							return d.completFlag === '是'?'已定价':'未定价';
						}}
						,{field: 'sfsw', title: '是否实物', minWidth:'100'}
						,{field: 'sfll', title: '是否来料', minWidth:'100'}
						,{field: 'llrq', title: '来料日期', minWidth:'120'}
						,{field: 'czjslx', title: '产值计算类型', minWidth:'120'}
						,{field: 'tsbz', title: '特殊备注', minWidth:'100'}
						,{fixed: 'right', title: '操作',toolbar: '#barRight'}
					]
				]
				,text: {
					none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
				}
				,data: []
				,toolbar:'#tableToolbar'
				,defaultToolbar: []
				,done: function(res,curr,count){
					for(var i in res.data){
						if(res.data[i].completFlag === '否'){
							$("tr[data-index='"+i+"']").attr({"style":"color:red","font-weight":"bold"})
						}
					}

					table.getRowData = function(tableId, elem){
						var index = $(elem).closest('tr').data('index');
						return table.cache[tableId][index] || {};
					};

					dropdown.render({
						elem: '.dropdpwn-demo',
						data: [{
							title: '正常结算',
							id: 0
						},{
							title: '异常结算',
							id: 1
						}],
						click: function(obj){
							let rowData = table.getRowData('table', this.elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
							this.elem.find('span').html(obj.title);
							// 更新数据中对应的字段
							rowData.settlementType = obj.id;
						}
					});
				}
			});

			table.on('row(table)', function(obj){
				obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');//选中行样式
				obj.tr.find('input[lay-type="layTableRadio"]').prop("checked",true);
				form.render('radio');
				selectId = obj.data.id;
				tableQty = obj.data.qty;
				//每次点击重新渲染
				let proData = produces.get(selectId);
				if (!proData){
					proData = []
				}
				table.reload('processTable',{
					data: proData
				})
			});

			table.render({
				elem:'#processTable'
				,page: true //开启分页
				,limit: 10
				,limits: [10,15,20,30,40,50,100]
				,loading: true
				,cols: [
					[ //表头
						{field: 'serialNumber', title: '序列号', minWidth:'50'}
						,{field: 'orderProcess', title: '订单工序', minWidth:'150'}
						,{field: 'orderProcessName', title: '工序名称', minWidth:'150'}
						,{field: 'sblx', title: '设备类型', minWidth:'90'}
						,{field: 'pricingMethod', title: '计价方式', minWidth:'150'}
						,{field: 'expectHours', title: '标准工时', minWidth:'150'}
						,{field: 'ioritaxcost', title: '价格', minWidth:'90'}
						,{field: 'qty', title: '合格数量', minWidth:'150', edit: true}
						,{field: 'unQty', title: '不合格数量', minWidth:'150', edit: true}
						,{field: 'jjfsje', title: '金额', minWidth:'120'}
					]
				]
				,text: {
					none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
				}
				,data: []
				,toolbar:'#processTableToolbar'
				,defaultToolbar: []
			});

			// 单元格编辑事件
			table.on('edit(processTable)', function(obj){
				let data = obj.data;
				let field = obj.field; // 得到修改的字段
				let value = obj.value // 得到修改后的值
				// 值的校验
				if(value.replace(/\s/g, '') === ''){
					layer.tips('值不能为空', this, {tips: 1});
					return obj.reedit(); // 重新编辑 -- v2.8.0 新增
				}
				// 更新当前缓存数据
				let update = {};
				if (field === 'qty'){
					if (Number.parseFloat(value) > Number.parseFloat(tableQty)){
						layer.tips('不能大于订单数量', this, {tips: 1});
						return obj.reedit(); // 重新编辑 -- v2.8.0 新增
					}
					let qty = Number.parseFloat(value) + Number.parseFloat(data.unQty)
					if (Number.parseFloat(qty) > Number.parseFloat(tableQty)){
						layer.tips('【合格数量】 + 【不合格数量】不能大于订单数量', this, {tips: 1});
						return obj.reedit(); // 重新编辑 -- v2.8.0 新增
					}
				}
				if (field === 'unQty'){
					if (Number.parseFloat(value) > Number.parseFloat(tableQty)){
						layer.tips('不能大于订单数量', this, {tips: 1});
						return obj.reedit(); // 重新编辑 -- v2.8.0 新增
					}
					let qty = Number.parseFloat(value)  + Number.parseFloat(data.qty)
					if (Number.parseFloat(qty) > Number.parseFloat(tableQty)){
						layer.tips('【合格数量】 + 【不合格数量】不能大于订单数量', this, {tips: 1});
						return obj.reedit(); // 重新编辑 -- v2.8.0 新增
					}
				}
				update[field] = value;
				obj.update(update, true); // 参数 true 为 v2.7 新增功能，即同步更新其他包含自定义模板并可能存在关联的列视图
			});

			table.on('edit(table)', function(obj){
				let data = obj.data;
				let field = obj.field; // 得到修改的字段
				let value = obj.value // 得到修改后的值
				// 值的校验
				if(value.replace(/\s/g, '') === ''){
					layer.tips('值不能为空', this, {tips: 1});
					return obj.reedit(); // 重新编辑 -- v2.8.0 新增
				}
				// 更新当前缓存数据
				let update = {};
				if (field === 'zkv'){
					update.zkv = value
				}
				update[field] = value;
				obj.update(update, true); // 参数 true 为 v2.7 新增功能，即同步更新其他包含自定义模板并可能存在关联的列视图
			});

			table.on('tool(table)', function(obj) {
				switch (obj.event) {
					case 'del':
						details = details.filter(o => o.id !== obj.data.id);
						//删除对应的工序
						produces.delete(obj.data.id)
						table.reload('table',{
							data: details
						})
						table.reload('processTable',{
							data: []
						})
						break;
				}
			})
			table.on('toolbar(table)', function(obj) {
				switch (obj.event) {
					case 'add':
						let saleOrderNoId = $('#saleOrderNoId').val();
						if (!saleOrderNoId){
							top.layer.msg("请先选择销售订单！")
							return false
						}
						top.layer.open({
							type: 2
							,title: "销售订单表体数据"
							,area: ['100%', '80%']
							,content: '/manage/sale_order_details/index/'+saleOrderNoId
							,btn: ['确定', '关闭']
							,yes: function (index, layero) {
								let iframeWindow = $(layero).find("iframe")[0].contentWindow;
								let obj = iframeWindow.fromData();
								let ids = new Set()
								let detailsIds = []
								obj.data.forEach(o => {
									//默认折扣率
									o.zkv = 100
									ids.add(o.masterId)
									detailsIds.push(o.mesId)
									//默认正常结算
									o.settlementType = 0
								})
								if (ids.size === 1){
									if (ids.keys().next().value !== saleOrderNoId){
										top.layer.msg("请正确选择数据！")
										return false
									}
									details = obj.data
									table.reload('table',{
										data: details
									})

									$.each(obj.data,function (ind,item) {
										//加载工序信息
										$.post(
												'manage/common/list/sale_order_process',
												{
													master: selectWhereEqual('details_id',item.mesId),
													page: -1,
													limit: -1
												},
												function (dd) {
													$.each(dd.data,function (inde,ite) {
														ite.unQty = 0
													})
													produces.set(item.id,dd.data)
													top.layer.close(index)
												}
										)
									})

								} else {
									top.layer.msg("请正确选择数据！")
								}
							}
						});
						break;
				}
			})
		})

		function fromData() {
			$('#submit').click();
		}

		function selectWhereEqual(field,val) {
			return JSON.stringify(
					[
						{
							"logicalOperator":"and",
							"rowlevel":"0",
							"conditionFieldVal":field,
							"conditionOptionVal":"equal",
							"conditionValueVal": { "value":val, "text":val }
						}
					]
			)
		}

	</script>
</div>
</body>
</html>